package study.lagou.com.jdbc;
import study.lagou.com.jdbc.pojo.User;
import java.sql.*;

/**
 * @Description: 功能描述
 * @Author houjh
 * @Email: happyxiaohou@gmail.com
 * @Date: 2021-1-25 23:32
 */
public class JDBCTest {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            //加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //通过驱动管理类获取到一个connection数据库连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&serverTimezone=UTC",
                    "root","111111");
            //编写对应的SQL语句，其中?表示参数的点位符
            String sql = "select * from user where username = ?";
            //通过connection获取到数据库预处理对象PreparedStatement
            preparedStatement = connection.prepareStatement(sql);
            //借助数据库预处理对象设置参数，第一个参数为SQL语句中参数的序号(从1开始)，第二个参数为设置的参数值
            preparedStatement.setString(1,"zhangsan");
            //向数据库发出SQL执行查询，查询出结果集
            resultSet = preparedStatement.executeQuery();
            //遍历查询的结果集
            while (resultSet.next()){
                int id = resultSet.getInt("id");
                String username = resultSet.getString("username");
                String password = resultSet.getString("password");
                String nickname = resultSet.getString("nickname");
                // 封装User
                User user = new User();
                user.setId(id);
                user.setUsername(username);
                user.setPassword(password);
                user.setNickname(nickname);
                System.out.println(user);
            }
        } catch (Exception e){
           e.printStackTrace();
        } finally {
            //释放资源
            if(resultSet != null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(preparedStatement != null){
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
